/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.ruoyi.project.module.api.service.impl;

import com.ruoyi.project.module.api.common.exception.ApiException;
import com.ruoyi.project.module.api.form.LoginForm;
import com.ruoyi.project.module.api.form.RegisterForm;
import com.ruoyi.project.module.api.service.AuthService;
import com.ruoyi.project.module.common.utils.AuthUtils;
import com.ruoyi.project.module.member.domain.Member;
import com.ruoyi.project.module.member.service.impl.MemberServicePlusImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;


@Service("authService")
public class AuthServiceImpl implements AuthService {

	@Autowired
	private MemberServicePlusImpl memberService;

	@Override
	public long login(LoginForm form) {
		Member member = memberService.selectMemberByMobile(form.getMobile());
		Assert.notNull(member, "手机号或密码错误");

		//密码错误

		String encodePassword = AuthUtils.encodePassword(form.getPassword());
		if(!member.getPassword().equals(encodePassword)){
			throw new ApiException("手机号或密码错误");
		}

		return member.getId();
	}

	@Override
	public long register(RegisterForm form) {

		Member member = memberService.selectMemberByMobile(form.getMobile());
		Assert.isNull(member, "手机号码已经被注册");

		member = new Member();
		member.setMobile(form.getMobile());
		member.setName(form.getMobile());
		member.setPassword(AuthUtils.encodePassword(form.getPassword()));
		member.setCreateTime(new Date());

		return memberService.insertMember(member);
	}

}
